<?php
/**
 * 数据库驱动层
 * @author yangzhiguo <yangzhiguo0903@163.com>
 */
defined('IN_LK') or die('Access Denied');
final class db_factory
{
	/**
	 * 实例化的类 用于实现析构
	 */
	public static $db_factory;
	
	/**
	 * 所有句柄
	 */
	public static $connids;
	
	/**
	 * 返回数据库句柄
	 */
	public static function initialize($db_name = '')
	{
		if(!self::$db_factory)
		{
			self::$db_factory = new db_factory;
		}
		if(!$db_name)
		{
			$db_name = DB_NAME;
		}
		if(!isset(self::$connids[$db_name]) || !is_object(self::$connids[$db_name]))
		{
			self::$connids[$db_name] = self::connect($db_name);
		}
		return self::$connids[$db_name];
	}
	
	/**
	 * 加载数据库驱动
	 * @param string $dbname 数据库名称
	 * @return object 数据库连接句柄
	 */
	private static function connect($dbname)
	{
		$object = null;
		switch(DB_TYPE)
		{
			case 'mysqli':
				//TODO
				break;
			case 'mysql':
			default:
				lk::lo('db_mysql', '', 0);
				$object = new db_mysql();
				break;
		}
		$object->connect(DB_HOST, DB_USER, DB_PASS, $dbname, DB_PCON, DB_CHAR);
		return $object;
	}
	
	/**
	 * 关闭所有数据库连接
	 */
	private static function close()
	{
		foreach(self::$connids as $db)
		{
			$db->close();
		}
		return true;
	}
	
	/**
	 * 析构函数
	 */
	public function __destruct()
	{
		self::close();
	}
}